const { app, shell, BrowserWindow, ipcMain } = require('electron')
const { join } = require('path')
const icon = join(__dirname, '../../resources/icon.png')

// 处理未捕获的异常
process.on('uncaughtException', (error) => {
  console.error('未捕获的异常:', error)
})

// 处理未处理的 Promise 拒绝
process.on('unhandledRejection', (reason, promise) => {
  console.error('未处理的 Promise 拒绝:', reason)
})

function createWindow() {
  // 创建浏览器窗口
  const mainWindow = new BrowserWindow({
    width: 500,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // 加载页面
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:5173')
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// 应用程序准备就绪时创建窗口
app.whenReady().then(() => {
  // 在 Windows 和 Linux 上，当所有窗口关闭时退出应用
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  createWindow()
})

// 处理选择 Cursor 路径
ipcMain.handle('select-cursor-path', async () => {
  try {
    const { dialog } = require('electron')
    const result = await dialog.showOpenDialog({
      properties: ['openFile'],
      filters: [{ name: '可执行文件', extensions: ['exe'] }]
    })

    if (!result.canceled && result.filePaths.length > 0) {
      const fs = require('fs')
      const path = require('path')
      const cursorPath = result.filePaths[0]
      const pathFile = path.join(app.getPath('userData'), 'cursor-path.txt')
      fs.writeFileSync(pathFile, cursorPath)
      return { 
        success: true, 
        data: cursorPath,
        message: '路径已保存'
      }
    }
    return { 
      success: false, 
      message: '用户取消了选择' 
    }
  } catch (error) {
    console.error('选择路径时出错:', error)
    return { 
      success: false, 
      message: error.message || '选择路径失败' 
    }
  }
})

// 处理获取 Cursor 路径
ipcMain.handle('get-cursor-path', async () => {
  try {
    const fs = require('fs')
    const path = require('path')
    const pathFile = path.join(app.getPath('userData'), 'cursor-path.txt')
    
    if (fs.existsSync(pathFile)) {
      const cursorPath = fs.readFileSync(pathFile, 'utf8')
      return { success: true, data: cursorPath }
    }
    return { success: false, message: '未找到 Cursor 路径' }
  } catch (error) {
    console.error('获取路径时出错:', error)
    return { success: false, message: error.message }
  }
})

// 处理 Cursor 操作
ipcMain.handle('handle-cursor', async (event, action) => {
  try {
    const fs = require('fs')
    const path = require('path')
    const { exec } = require('child_process')
    const pathFile = path.join(app.getPath('userData'), 'cursor-path.txt')

    if (!fs.existsSync(pathFile)) {
      return { success: false, message: '请先选择 Cursor 程序路径' }
    }

    const cursorPath = fs.readFileSync(pathFile, 'utf8')
    const cursorDir = path.dirname(cursorPath)
    
    // 删除用户登录状态相关文件
    const userDataPath = path.join(cursorDir, 'resources', 'app', 'user-data')
    const sessionPath = path.join(cursorDir, 'resources', 'app', 'session')
    const loginPath = path.join(cursorDir, 'resources', 'app', 'login')
    const authPath = path.join(cursorDir, 'resources', 'app', 'auth')
    
    // 先关闭 Cursor 进程
    exec('taskkill /F /IM Cursor.exe', async (error) => {
      // 忽略关闭进程的错误，因为进程可能本来就没有运行
      try {
        // 删除所有用户相关数据
        if (fs.existsSync(userDataPath)) {
          fs.rmSync(userDataPath, { recursive: true, force: true })
        }
        if (fs.existsSync(sessionPath)) {
          fs.rmSync(sessionPath, { recursive: true, force: true })
        }
        if (fs.existsSync(loginPath)) {
          fs.rmSync(loginPath, { recursive: true, force: true })
        }
        if (fs.existsSync(authPath)) {
          fs.rmSync(authPath, { recursive: true, force: true })
        }
      } catch (err) {
        console.error('删除用户数据时出错:', err)
        return { success: false, message: '删除用户数据失败: ' + err.message }
      }
    })
    
    return { success: true, message: 'Cursor 已退出并清除用户数据' }
  } catch (error) {
    console.error('处理 Cursor 操作时出错:', error)
    return { success: false, message: error.message }
  }
})

// 处理打开 Cursor 网站
ipcMain.handle('open-cursor-website', async () => {
  try {
    await shell.openExternal('https://cursor.sh')
    return { success: true, message: '已打开 Cursor 网站' }
  } catch (error) {
    console.error('打开网站时出错:', error)
    return { success: false, message: error.message }
  }
})

// 处理删除 Cursor 账号
ipcMain.handle('delete-cursor-account', async () => {
  try {
    await shell.openExternal('https://cursor.sh')
    return { success: true, message: '已打开 Cursor 网站，请手动删除账号' }
  } catch (error) {
    console.error('打开网站时出错:', error)
    return { success: false, message: error.message }
  }
})

// 处理重置 Cursor 机器码
ipcMain.handle('reset-cursor-machine-code', async () => {
  try {
    const fs = require('fs')
    const path = require('path')
    const pathFile = path.join(app.getPath('userData'), 'cursor-path.txt')

    if (!fs.existsSync(pathFile)) {
      return { success: false, message: '请先选择 Cursor 程序路径' }
    }

    const cursorPath = fs.readFileSync(pathFile, 'utf8')
    const cursorDir = path.dirname(cursorPath)
    const machineCodeDir = path.join(cursorDir, 'resources', 'app', 'machine-code')

    if (fs.existsSync(machineCodeDir)) {
      fs.rmSync(machineCodeDir, { recursive: true, force: true })
      return { success: true, message: '重置机器码成功!' }
    } else {
      return { success: true, message: '续杯成功' }
    }
  } catch (error) {
    console.error('重置机器码时出错:', error)
    return { success: false, message: error.message }
  }
})

// 处理禁止 Cursor 更新
ipcMain.handle('stop-cursor-update', async () => {
  try {
    const fs = require('fs')
    const path = require('path')
    const { exec } = require('child_process')

    // hosts 文件路径
    const hostsPath = process.platform === 'win32' 
      ? 'C:\\Windows\\System32\\drivers\\etc\\hosts'
      : '/etc/hosts'

    // 读取当前 hosts 文件内容
    let hostsContent = fs.readFileSync(hostsPath, 'utf8')

    // 检查是否已经添加了阻止规则
    if (hostsContent.includes('cursor.sh')) {
      return { success: true, message: '已经禁止了 Cursor 更新' }
    }

    // 添加阻止规则
    const blockRules = [
      '\n# Cursor Update Block',
      '127.0.0.1 cursor.sh',
      '127.0.0.1 update.cursor.sh',
      '127.0.0.1 api.cursor.sh'
    ].join('\n')

    // 写入新的 hosts 文件内容
    fs.writeFileSync(hostsPath, hostsContent + blockRules, 'utf8')

    // 刷新 DNS 缓存
    if (process.platform === 'win32') {
      exec('ipconfig /flushdns', (error) => {
        if (error) {
          console.error('刷新 DNS 缓存失败:', error)
        }
      })
    }

    return { success: true, message: '已成功禁止 Cursor 更新' }
  } catch (error) {
    console.error('禁止更新时出错:', error)
    return { 
      success: false, 
      message: '禁止更新失败，请确保以管理员权限运行程序: ' + error.message 
    }
  }
})
